# 黑神话悟空wukong 地图测绘 by:旧城doit
# 使用说明 打开游戏进入存档后，运行这个插件，然后开始跑图会自动记录玩家位置，位置记录完成后，按T键停止记录，就会输出png和地图坐标json文件
from MemRead import *
import json
import time
import threading
import keyboard
from PIL import Image

class PlayerPositionTracker:
    def __init__(self):
        self.poslist = []
        self.running = True

    def start_tracking(self):
        threading.Thread(target=self.track_position).start()

    def track_position(self):
        while self.running:
            x, y = self.get_player_position()
            self.poslist.append((x, y))
            time.sleep(0.016)  # 16 milliseconds

    def get_player_position(self):
        t_x = int(mem.read(mem.base_address + 0x1D493BFC - 4, 4,"float") / 40 )
        t_y = int(mem.read(mem.base_address + 0x1D493BFC - 8, 4,"float") / 40 ) * -1
        return (t_x, t_y)

    def save_positions(self):
        with open('poslist.json', 'w') as f:
            json.dump(self.poslist, f)

    def draw_pixel_squares(self, img, top_left,color):
        for i in range(15):
            for j in range(15):
                img.putpixel((top_left[0] + i, top_left[1] + j), color)

    def create_and_export_map(self):
        # Create a 2048x2048 transparent canvas
        img = Image.new('RGBA', (8192, 8192), (255, 255, 255, 0))
        for pos in self.poslist:
            # Draw a 5x5 black pixel square at each position
            self.draw_pixel_squares(img, (pos[0] + 4096, pos[1] + 4096),(0, 0, 0, 255))
        self.draw_pixel_squares(img, (self.poslist[0][0] + 4096, self.poslist[0][1] + 4096), (255, 0, 0, 255))
        self.draw_pixel_squares(img, (self.poslist[-1][0] + 4096, self.poslist[-1][1] + 4096), (0, 255, 0, 255))
        img.save('map_output.png')

# 创建应用程序对象
pro_name = "b1-Win64-Shipping.exe"
mem = MemRead(pro_name)
tracker = PlayerPositionTracker()
tracker.start_tracking()

# Wait for the 'T' key to be pressed to save and export
keyboard.wait('t')
print("Saving positions...")
tracker.running = False  
tracker.save_positions()
tracker.create_and_export_map()
